package com.dao.impl;

import com.dao.UserDao;
import com.pojo.User;
import com.utils.DBUtils;
import com.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.*;

public class UserDaoImpl implements UserDao {
    private static final String SELECT_USERNAME_SQL="select id,username,email,password,name,phone,address,isadmin,isvalidate from user where username=?";
    private static final String SELECT_EMAIL_SQL="select id,username,email,password,name,phone,address,isadmin,isvalidate from user where email=?";

    private static final String INSEET_USER_SQL="insert into user(username,email,password,name,phone,address,isadmin,isvalidate) values(?,?,?,?,?,?,?,?)";
    //    判断是否用户名相同
    @Override
    public boolean isUsernameExist(String username) throws Exception {
        try(Connection connection = DBUtils.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USERNAME_SQL)) {
            preparedStatement.setString(1,username);
            ResultSet rs = preparedStatement.executeQuery();
            if(rs.next()){
                return true;
            }
            else {
                return false;
            }
        }
    }

    //    判断是否email相同
    @Override
    public boolean isEmailExist(String email)throws Exception {
        try(Connection connection = DBUtils.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(SELECT_EMAIL_SQL)) {
            preparedStatement.setString(1,email);
            ResultSet rs = preparedStatement.executeQuery();
            if(rs.next()){
                return true;
            }
            else {
                return false;
            }
        }
    }
    //    添加用户
    @Override
    public User addUser(User user) throws Exception{
        try (Connection connection = DBUtils.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(INSEET_USER_SQL, Statement.RETURN_GENERATED_KEYS)){
            preparedStatement.setString(1,user.getUsername());
            preparedStatement.setString(2, user.getEmail());
            preparedStatement.setString(3, user.getPassword());
            preparedStatement.setString(4, user.getName());
            preparedStatement.setString(5, user.getPhone());
            preparedStatement.setString(6, user.getAddress());
            preparedStatement.setBoolean(7,user.isIsadmin());
            preparedStatement.setBoolean(8,user.isIsvalidate());
            preparedStatement.executeUpdate();
            ResultSet rs = preparedStatement.getGeneratedKeys();
            while (rs.next()){
                user.setId(rs.getInt(1));
                return user;
            }
        }
        return null;
    }
}
